<template>
	<div class="system-role-container">
		<el-dialog title="新增角色" v-model="isShowDialog" width="80%">
			<el-form ref="addRoleFormRef" :model="formData" :rules="formRules" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色名称" prop="roleName">
							<el-input v-model="formData.roleName" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="权限字符" prop="roleKey">
							<el-input v-model="formData.roleKey" placeholder="请输入角色权限字符" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择角色状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色排序" prop="orderNum">
							<el-input-number v-model="formData.orderNum" :min="0" :max="999" clearable class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-divider content-position="left">角色-菜单权限授权</el-divider>
					<el-col>
						<el-form-item label="菜单权限">
							<el-cascader
								placeholder="请选择菜单权限（可选填）"
								v-model="formData.menuIds"
								:options="menus"
								:props="{expandTrigger: 'hover', multiple: true, value: 'id', label: 'menuName', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-divider content-position="left">角色-数据权限授权</el-divider>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="数据权限" prop="dataScope">
							<el-select v-model="formData.dataScope" placeholder="请选择数据权限" clearable class="w100">
								<el-option label="全部数据权限" value="1"></el-option>
								<el-option label="仅本用户数据权限" value="5"></el-option>
								<el-option label="自定义数据权限" value="2"></el-option>
								<el-option label="本部门及以下数据权限" value="4"></el-option>
								<el-option label="本部门数据权限" value="3"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="数据范围" prop="deptIds">
							<el-cascader
								placeholder="请选择自定义数据权限范围（可选填）"
								v-model="formData.deptIds"
								:disabled="formData.dataScope !== '2'"
								:options="depts"
								:props="{expandTrigger: 'hover', multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'deptName', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-divider content-position="left">业务-数据权限授权</el-divider>
					<el-col>
						<el-table ref="tableBusinessScopeRef" :data="formData.businessScopes" style="width: 100%" row-key="id">
							<el-table-column type="index" align="center" width="50" show-overflow-tooltip></el-table-column>
							<el-table-column label="业务类型" prop="business" min-width="150" show-overflow-tooltip>
								<template #default="scope">
									<el-form-item :prop="`businessScopes.${scope.$index}.business`" :rules="[{ required: true, message: `业务类型不能为空`, trigger: 'change' }]" :inline-message="true" label-width="0px" style="margin-bottom: 0px;">
										<Dictionary v-model="scope.row.business" dict-label="sys_data_scope" placeholder="请选择业务类型"></Dictionary>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="数据权限" prop="dataScope" min-width="150" show-overflow-tooltip>
								<template #default="scope">
									<el-form-item :prop="`businessScopes.${scope.$index}.dataScope`" :rules="[{ required: true, message: `数据权限不能为空`, trigger: 'change' }]" :inline-message="true" label-width="0px" style="margin-bottom: 0px;">
										<el-select v-model="scope.row.dataScope" placeholder="请选择数据权限" clearable class="w100">
											<el-option label="全部数据权限" value="1"></el-option>
											<el-option label="仅本用户数据权限" value="5"></el-option>
											<el-option label="自定义数据权限" value="2"></el-option>
											<el-option label="本部门及以下数据权限" value="4"></el-option>
											<el-option label="本部门数据权限" value="3"></el-option>
										</el-select>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="数据范围" prop="deptIds" min-width="200" show-overflow-tooltip>
								<template #default="scope">
									<el-form-item :prop="`businessScopes.${scope.$index}.deptIds`" :rules="[{ required: true, validator: validBusinessDeptIds, trigger: 'change' }]" :inline-message="true" label-width="0px" style="margin-bottom: 0px;">
										<el-cascader
											placeholder="请选择自定义数据权限范围（可选填）"
											v-model="scope.row.deptIds"
											:disabled="scope.row.dataScope !== '2'"
											:options="depts"
											:props="{expandTrigger: 'hover', multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'deptName', children: 'children' }"
											collapse-tags
											class="w100"
											clearable>
										</el-cascader>
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column show-overflow-tooltip width="80">
								<template #header>
									<el-button type="primary" link @click="onAddBusinessScope()">
										<svg-icon name="el-icon-document-add" style="cursor: pointer;"></svg-icon>
									</el-button>
								</template>
								<template #default="scope">
									<el-button type="danger" link @click="onDelBusinessScope(scope.row)">
										<svg-icon name="el-icon-delete" style="cursor: pointer;"></svg-icon>
									</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addRole } from '/@/api/system/role/index';
import { getMenuList } from '/@/api/system/menu/index';
import { getDeptList } from '/@/api/system/dept/index';
import { verifyStringCode } from '/@/utils/toolsValidate';
import { lineToTreeData } from '/@/utils/commonFunction';
import Dictionary from '/@/components/dictionary/index.vue';
export default {
	name: 'role/add',
	components: { Dictionary },
	setup(props, context) {
		const addRoleFormRef = ref();
		const validRoleKey = (rule, value, callback) => {
			if(!value){
				return callback(new Error('权限字符不能为空'));
			}
			if(!verifyStringCode(value)){
				return callback(new Error('只允许字母或数字或下划线组成5~16个字符'));
			}
			callback();
		}
		const validDeptIds = (rule, value, callback) => {
			if(state.formData.dataScope == '2'){
				if(!value || value.length == 0){
					return callback(new Error('自定义数据范围不能为空'));
				}
			}
			callback();
		}
		const validBusinessDeptIds = (rule, value, callback) => {
			if(rule.field.indexOf('businessScopes') != -1){
				if(state.formData.businessScopes[rule.field.split('.')[1]].dataScope == '2'){
					if(!value || value.length == 0){
						return callback(new Error('自定义数据范围不能为空'));
					}
				}
			}
			callback();
		}
		
		const state = reactive({
			isShowDialog: false,
			menus: [],
			depts: [],
			formData: {
				dataScope: '',
				menuIds: [],
				deptIds: [],
				orderNum : 1,
				businessScopes: [],
			},
			formRules : {
				status: { required: true, message: '角色状态不能为空', trigger: 'change' },
				roleName: { required: true, message: '角色名称不能为空', trigger: 'blur' },
				roleKey: { required: true, validator: validRoleKey, trigger: 'blur' },
				dataScope: { required: true, message: '数据权限不能为空', trigger: 'change' },
				deptIds: { required: true, validator: validDeptIds, trigger: 'change' },
				orderNum: { required: true, message: '角色排序不能为空', trigger: 'blur' }
			}
		});

		//初始化菜单级联
		const loadMenus = async () => {
			await getMenuList({isCommon: 'N'}).then((res) => {
				if(res.code == 0){
					state.menus = lineToTreeData(res.data);
				}
			});
		}
		//初始化部门级联
		const loadDepts = async () => {
			await getDeptList().then((res) => {
				if(res.code == 0){
					state.depts = lineToTreeData(res.data);
				}
			});
		}
		// 打开弹窗
		const openDialog = (row?: object) => {
			state.isShowDialog = true;
			state.formData.menuIds = [];
			state.formData.deptIds = [];
			loadMenus();
			loadDepts();
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			addRoleFormRef.value.resetFields();
			state.formData.businessScopes = [];
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
			addRoleFormRef.value.validate(valid => {
				if(valid){
					let menuIds = [],deptIds = [];
					state.formData.menuIds.forEach(items => {
						if(typeof items == 'string'){
							menuIds.push(items);
						}else{
							items.forEach(item => {
								menuIds.push(item);
							});
						}
					});
					menuIds = Array.from(new Set(menuIds));//去重

					state.formData.deptIds.forEach(items => {
						if(typeof items == 'string'){
							deptIds.push(items);
						}else{
							items.forEach(item => {
								deptIds.push(item);
							});
						}
					});
					deptIds = Array.from(new Set(deptIds));//去重

					state.formData.businessScopes.forEach(items => {
						let businessDeptIds = [];
						items.deptIds.forEach(item => {
							if(typeof item == 'string'){
								businessDeptIds.push(item);
							}else{
								item.forEach(items => {
									businessDeptIds.push(items);
								});
							}
						});
						items.deptIds = Array.from(new Set(businessDeptIds));//去重
					});

					let params = {
						status: state.formData.status,
						roleName: state.formData.roleName,
						roleKey: state.formData.roleKey,
						orderNum: state.formData.orderNum,
						remark: state.formData.remark,
						menuIds: menuIds,
						dataScope: state.formData.dataScope,
						deptIds: deptIds,
						businessScopes: state.formData.businessScopes
					}
					addRole(params).then((res) => {
						if(res.code === 0){
							ElMessage.success('保存成功');
							context.emit('submit');
							closeDialog();
						}
					});
				}
			});
		};

		const onAddBusinessScope = () => {
			state.formData.businessScopes.push({
				business: '',
				roleId: state.formData.id,
				dataScope: '',
				deptIds: []
			});
		}
		const onDelBusinessScope = (row: any) => {
			ElMessageBox.confirm('确定要删除数据吗？', '提示', {
				type: 'warning',
			}).then(() => {
				let index = state.formData.businessScopes.indexOf(row);
				state.formData.businessScopes.splice(index, 1);
			}).catch(() => {});
		}
		return {
			addRoleFormRef,
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			onAddBusinessScope,
			onDelBusinessScope,
			validBusinessDeptIds,
			...toRefs(state),
		};
	},
};
</script>